<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 基地详情
 *
 * @author      Eden
 * @datetime    2016/12/18 16:22
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Detail_Model extends API_Model
{

    // 基地ID
    private $baseId = 0;

    // 缩略图宽高
    protected $width = 640;
    protected $height = 360;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {
            if (empty($params['baseId'])) {
                $send['error'] = '基地不存在';
                break;
            }

            $this->baseId = $params['baseId'];
            if ($params['type'] == 'android') {
                $this->width = $this->width / 2;
                $this->height = $this->height / 2;
            }

            $detail = $this->getBaseDetail();
            if (!$detail) {
                $send['error'] = $this->getError();
                break;
            }

            // 基地下的产品
            $this->_getGoodsInBase($detail);
            // 相关产品
            $this->_getRelatedInBase($detail);

            @statIncr('pv');

            $send['state'] = true;
            $send['data'] = $detail;

        }while(false);
        $this->output->send($send);
    }

    /**
     * 相关产品
     * @param $detail
     * @return bool
     */
    protected function _getRelatedInBase(&$detail)
    {
        $detail['related'] = array(
            'total' => 0,
            'data' => []
        );
        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, liveUrl, bannerThumb, recommendThumb, thumbWidth,
        thumbHeight, streamId, minPrice, minPurPrice, created')
            ->from('base_goods')
            ->order_by('pv', 'DESC')
            ->limit(8)
            ->where(array('status' => 1))
            ->where('stock > 0')
            ->where_not_in('id', array($this->baseId))
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return false;
        }

        $results = $this->_doAfterSelectGoods($rows);
        $detail['related']['total'] = count($results);
        $detail['related']['data'] = $results;
    }



    /**
     * 处理返回结果
     * @param array $goods
     * @return array
     */
    private function _doAfterSelectGoods($goods = array(), $selfGoods = false)
    {
        $results = [];
        foreach($goods as $item) {
            if ($selfGoods) {
                $width = 200;
                $height = 300;
                $thumb = !empty($item['recommendThumb']) ? $item['recommendThumb'] : $item['thumb'];
            } else {
                $wh = $this->countWidthHeight($item['thumbWidth'], $item['thumbHeight']);
                $width = (int) $wh['width'];
                $height = (int) $wh['height'];
                $thumb = $item['thumb'];
            }
            $thumb = thumb($thumb, $width, $height);
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => $thumb,
                'width' => $width,
                'height' => $height,
                'price' => money_format('%i', $item['minPrice']),
                'created' => formateTimeStamp($item['created']),
                'isLive' => !empty($item['liveUrl']),
                'liveUrl' => value($item, 'liveUrl'),
            );
        }
        return $results;
    }

    /**
     * 该基地下的产品
     * @param $detail
     * @return bool
     */
    protected function _getGoodsInBase(&$detail)
    {
        $detail['goods'] = array(
            'total' => 0,
            'data' => []
        );
        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, liveUrl, bannerThumb, recommendThumb,
        thumbWidth, thumbHeight, streamId, minPrice, minPurPrice, created')
            ->from('base_goods')
            ->order_by('likes', 'DESC')
            ->limit(8)
            ->where(array('status' => 1, 'baseId' => $this->baseId))
            ->where("stock > 0")
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return false;
        }

        $results = $this->_doAfterSelectGoods($rows, true);
        $detail['goods']['total'] = count($results);
        $detail['goods']['data'] = $results;
    }

    /**
     * 获取详情
     * @return array|bool
     */
    protected function getBaseDetail()
    {
        $db = clone($this->db);
        $q = $db->select('name, content, thumb, liveUrl, streamId, pv, createdBy, created')
            ->where('id', $this->baseId)
            ->get('base');
        $row = $q->row_array();
        if (empty($row)) {
            $this->setError('农场不存在');
            return false;
        }

        $row['live'] = array(
            'status' => false,
            'address' => new stdClass()
        );

        if (!empty($row['streamId'])) {
            $stream = $this->_getStreamInfo($row['streamId']);
            if (!empty($stream)) {
                $status = $stream['status'] == 1;
                $row['live'] = array(
                    'status' => $status,
                    'address' => !$status ? new stdClass() : array(
                        'hd' => $stream['videoUrlHD'],
                        'sd' => $stream['videoUrlSD']
                    )
                );
            }
        }

        // 修改PV
        $this->addPv('base', array('id' => $this->baseId), $row['pv']);

        return array(
            'baseId' => intval($this->baseId),
            'baseName' => value($row, 'name'),
            'thumb' => thumb($row['thumb'], $this->width, $this->height),
            'live' => $row['live'],
            'isLive' => !empty($row['liveUrl']),
            'liveUrl' => value($row, 'liveUrl', ''),
            'pv' => intval($row['pv']) + 1,
            'created' => formateTimeStamp($row['created']),
            'content' => $this->_content($row['name'], $row['content'])
        );
    }

    /**
     * 渲染详情页
     * @param $title
     * @param $content
     * @return mixed
     */
    private function _content($title, $content)
    {
        return $this->load->view('app/base/detail.html', array(
            'title' => $title,
            'content' => $content
        ), true);
    }

    /**
     * 直播
     * @param int $streamId
     * @return mixed
     */
    private function _getStreamInfo($streamId = 0)
    {
        $db = clone($this->db);
        $q = $db->select('videoUrlHD, videoUrlSD, status')->get_where('stream_device', array('id' => $streamId));
        return $q->row_array();
    }

}
